package com.lyx.crm.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyx.crm.base.BaseService;
import com.lyx.crm.dao.CustomerMapper;
import com.lyx.crm.query.CustomerQuery;
import com.lyx.crm.utils.AssertUtil;
import com.lyx.crm.utils.PhoneUtil;
import com.lyx.crm.vo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Package: com.lyx.crm.service
 * @ClassName: CustomerService
 * @Author: lyx
 * @CreateTime: 2021/10/3 16:37
 * @Description:
 */
@Service
public class CustomerService extends BaseService<Customer, Integer> {

    @Autowired
    private CustomerMapper customerMapper;

    /**
     * 多条件查询营销机会  （返回的数据格式必须满足LayUI中数据表格要求的格式）
     *
     * @param customerQuery
     * @return
     */
    public Map<String, Object> queryCustomerByParams(CustomerQuery customerQuery) {

        Map<String, Object> map = new HashMap<>();

        // 开启分页
        PageHelper.startPage(customerQuery.getPage(), customerQuery.getLimit());
        // 得到对应分页对象
        PageInfo<Customer> pageInfo = new PageInfo<>(customerMapper.selectByParams(customerQuery));

        // 设置map对象
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", pageInfo.getTotal());
        // 设置分页好的列表
        map.put("data", pageInfo.getList());

        return map;
    }

    /**
     * 添加客户信息操作
     *
     * 参数校验
     *        客户姓名
     *          非空，唯一
     *        公司名称
     *          非空，唯一
     *       手机号
     *          非空，格式正确
     *        法人代表
     *             非空
     * @param customer
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addCustomer(Customer customer) {
        //校验客户信息
        checkCustomerParams(customer.getName(), customer.getFr(), customer.getPhone());

        //判断客户唯一性
        Customer temp = customerMapper.queryCustomerByName(customer.getName());

        AssertUtil.isTrue(temp != null, "客户名称已存在，请重新输入！");

        /*设置默认值*/
        customer.setCreateDate(new Date());
        customer.setUpdateDate(new Date());

        /*客户编号*/
        String khno = "KH" + System.currentTimeMillis();//时间戳
        customer.setKhno(khno);


        AssertUtil.isTrue(customerMapper.insertSelective(customer) < 1, "添加客户失败");

    }

    /**
     * @param name
     * @param fr
     * @param phone
     */
    private void checkCustomerParams(String name, String fr, String phone) {
        AssertUtil.isTrue(StrUtil.isBlankIfStr(name), "客户名称不能为空");

        AssertUtil.isTrue(StrUtil.isBlankIfStr(fr), "公司名称不能为空");

        AssertUtil.isTrue(StrUtil.isBlankIfStr(phone), "手机号不能为空");

        AssertUtil.isTrue(!PhoneUtil.isMobile(phone), "手机号格式不正确");

    }
}
